const {
  weix: { appid, secret, serverToken, baseURL, QRcode },
} = require("../config");
const { sha1 } = require("./common/screct");
const axios = require("axios").create({
  baseURL: baseURL,
});
// const { getAccessToken } = require('./weix')
let tokenBuff = {};

exports.sign = async function (url) {
  await getJsapiTicket();
  let obj = {
    nonceStr: getRandomStr(16),
    timestamp: getTimestamp(),
  };

  let str = "";
  let newObj = Object.assign({ jsapi_ticket: tokenBuff.ticket, url }, obj);
  const keys = Object.keys(newObj);
  keys.sort().forEach((key, index) => {
    str += `${index ? "&" : ""}${key.toLowerCase()}=${newObj[key]}`;
  });

  obj.appId = appid;
  obj.signature = sha1(str);
  console.log(tokenBuff);
  return obj;
};

const getRandomStr = function (num) {
  let str = Math.random().toFixed(num);
  return str.substr(2);
};
const getTimestamp = function () {
  return parseInt(new Date().getTime() / 1000);
};

exports.checkEditWxServerConfigRequest = function (
  signature,
  timestamp,
  nonce
) {
  var tmpArr = [serverToken, timestamp, nonce];
  tmpArr.sort();
  var tmpStr = tmpArr.join("");
  tmpStr = sha1(tmpStr);
  console.log(tmpStr, signature, tmpStr === signature);
  return tmpStr === signature;
};

const getAccessToken = function () {
  return axios
    .get("cgi-bin/token", {
      params: {
        appid,
        secret,
        grant_type: "client_credential",
      },
    })
    .then((res) => {
      if (!res.data.errcode) {
        return res.data;
      } else {
        throw Error(`getAccessToken(): ${res.data.errcode} ${res.data.errmsg}`);
      }
    });
};

const fs = require("fs").promises;
const getJsapiTicket = async function () {
  try {
    if (!(await isValid("ticket"))) {
      console.log("getJsapiTicket 主动获取");
      const info = await getAccessToken();
      tokenBuff.access_token = info.access_token;
      const ticket = await axios
        .get("cgi-bin/ticket/getticket", {
          params: {
            access_token: tokenBuff.access_token,
            type: "jsapi",
          },
        })
        .then((res) => {
          if (res.data.errcode === 0) {
            return res.data;
          } else {
            throw Error(`getJsapiTicket(): ${res.data.errmsg}`);
          }
        });
      tokenBuff.ticket = ticket.ticket;
      tokenBuff.time = new Date().getTime();
      await fs.writeFile("./config/db.json", JSON.stringify(tokenBuff));
    }
    return tokenBuff.ticket;
  } catch (error) {
    console.log("getJsapiTicket", error.message);
  }
};

const isValid = async function (key) {
  const validTypes = ["token", "ticket"];
  if (key === undefined) {
    key = validTypes[0];
  } else if (typeof key !== "string") throw Error("key 不为String 类型");
  else if (validTypes.indexOf(key) == -1)
    throw Error("当前不支持key 的值" + key);

  try {
    if (!tokenBuff[key]) {
      const file = await fs.readFile("./config/db.json");
      if (!!file.length) {
        tokenBuff = JSON.parse(file.toString());
        console.log("tokenBUff is buff");
      }
    }
    if (
      !tokenBuff[key] ||
      (!!tokenBuff.time && new Date().getTime() - tokenBuff.time > 7000 * 1000)
    ) {
      return false;
    }
    return true;
  } catch (e) {
    console.log("isValid()", e.message);
  }
};

exports.axios = axios;

/**
 * 返回最新token
 */
exports.getToken = async function () {
  await getJsapiTicket();
  return tokenBuff.access_token;
};
